package com.app.samba.play;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.app.samba.DebugLog;
import com.app.samba.R;
import com.app.samba.play.service.PlayFileService;
import com.app.samba.play.util.FileItem;
import com.app.samba.play.util.FileUtil;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;


public class PlayfileActivity extends Activity implements OnItemClickListener {
    private EditText ip = null;
    private Button add = null;
    private ListView list = null;
    private ProgressDialog dialog = null;
    private ArrayAdapter<FileItem> adapter = null;
    private ArrayList<FileItem> al = new ArrayList<FileItem>();
    private SearchTask task = null;
    private String root = "/";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        Intent intent = new Intent(this, PlayFileService.class);
        startService(intent);
        init();
    }

    private void init() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在努力加载...");
        dialog.setCanceledOnTouchOutside(false);
        al.add(new FileItem("...", root, false));
        add = (Button) findViewById(R.id.add);
        ip = (EditText) findViewById(R.id.ip);
        list = (ListView) findViewById(R.id.list);
        adapter = new ArrayAdapter<FileItem>(this,
                android.R.layout.simple_list_item_1, al);
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String ipValue = ip.getText().toString();
                adapter.add(new FileItem(ipValue, "smb://" + ipValue + "/",
                        false));
                root = "smb://" + ipValue + "/";
                /**或者直接使用下面    指定自己要访问的单个文件路径*/
//				String ipValues = ip.getText().toString();
//				ipValue = "smb://192.168.43.117/mkv/abc.mp4";
//
//				try {
//					NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
//							"192.168.43.117", "xiaoniao", "heimi123456,");
//					SmbFile smbFile = new SmbFile(ipValues);//
//					String ipVal = FileUtil.ip;
//					int portVal = FileUtil.port;
//					String path = smbFile.getPath();
//					String httpReq = "http://" + ipVal + ":" + portVal
//							+ "/smb:";
//					Log.e("", "" + FileUtil.ip + ":" + FileUtil.port + " "
//							+ path);
//					Log.v("httpReq", "httpReq: " + httpReq);
//					if (path.endsWith(".mp4")) {
//						path = path.substring(6);
//						try {
//							path = URLEncoder.encode(path, "UTF-8");
//						} catch (UnsupportedEncodingException e) {
//							e.printStackTrace();
//						}
//
//						String url = httpReq + path;
//						Log.v("url=", "url: " + url);
//						System.out.println(url);
//						Intent it = new Intent(Intent.ACTION_VIEW);
//						Uri uri = Uri.parse(url);
//						it.setDataAndType(uri, "video/mp4");
//						startActivity(it);
//
//					}
//				} catch (MalformedURLException e) {
//					// TODO Auto-generated catch block
//					Log.v("","", e);
//				}
//
//				root = "smb://" + ipValue + "/";
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        FileItem fileItem = al.get(position);
        if (fileItem.isFile()) {
            String ipVal = FileUtil.ip;
            int portVal = FileUtil.port;
            String path = fileItem.getPath();

            String httpReq = "http://" + ipVal + ":" + portVal + "/smb=";
            // String httpReq = "http://" + ip + ":" + port + "/smb=";
            DebugLog.d(DebugLog.SAMBA_LOG + FileUtil.ip + ":" + FileUtil.port + " " + path);
            if (path.endsWith(".mp3")) {
                path = path.substring(6);
                try {
                    path = URLEncoder.encode(path, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String url = httpReq + path;
                DebugLog.d(DebugLog.SAMBA_LOG +"url: " + url);
                playAudio(url,this);

            } else {
                path = path.substring(6);
                try {
                    path = URLEncoder.encode(path, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String url = httpReq + path;
                DebugLog.d(DebugLog.SAMBA_LOG +"url: " + url);
                Intent it = new Intent(Intent.ACTION_VIEW);
                Uri uri = Uri.parse(url);
                it.setDataAndType(uri, "video/mp4");
                startActivity(it);
            }
        } else {
            //文件夹
            String path = fileItem.getPath();

            searchFile(path);
        }
    }

    private void searchFile(String path) {
        if (task == null || task.getStatus().equals(AsyncTask.Status.FINISHED)) {
            new SearchTask().execute(path);
        }

    }

    class SearchTask extends AsyncTask<String, Void, Void> {
        ArrayList<FileItem> item = new ArrayList<FileItem>();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.show();
        }

        @Override
        protected Void doInBackground(String... params) {
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
                    "192.168.31.76", "administrator", "065021");
            try {
                DebugLog.d(DebugLog.SAMBA_LOG+"sam地址 "+params[0]);
                SmbFile smbFile = new SmbFile(params[0],auth);
                ArrayList<SmbFile> dirList = new ArrayList<SmbFile>();
                ArrayList<SmbFile> fileList = new ArrayList<SmbFile>();
                SmbFile[] fs = smbFile.listFiles();
                for (SmbFile f : fs) {
                    if (f.isDirectory()) {
                        dirList.add(f);
                    } else {
                        fileList.add(f);
                    }
                }
                dirList.addAll(fileList);
                for (SmbFile f : dirList) {
                    String filePath = f.getPath();
                    String fileName = f.getName();
                    boolean isFile = f.isFile();
                    Log.e("", "fileName: " + fileName + " " + filePath
                            + " isFile: " + isFile);
                    item.add(new FileItem(fileName, filePath, isFile));
                }
            } catch (MalformedURLException | SmbException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (!item.isEmpty()) {
                adapter.clear();
                adapter.add(new FileItem("...", root, false));
                for (FileItem i : item) {
                    adapter.add(i);
                }
            } else {
                Toast.makeText(PlayfileActivity.this, "加载失败了，请重试 ",
                        Toast.LENGTH_SHORT).show();
            }
            dialog.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(this, PlayFileService.class);
        stopService(intent);
    }
    /**
     * 打开系统播放器
     * @param audioPath 指定默认播放的音乐
     */
    public  void playAudio(String audioPath,Context context){
        Intent mIntent = new Intent();
        mIntent.setAction(android.content.Intent.ACTION_VIEW);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.parse(audioPath);
        mIntent.setDataAndType(uri , "audio/mp3");
        context.startActivity(mIntent);
    }
}